package org.example.middownloadtool.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Objects;
import java.util.UUID;

public class DownloadService extends Thread{

    private String uri;
    private String folderPath;
    private String width;
    private String height;
    private String format;

    public DownloadService(String uri, String folderPath,String width,String height,String format) {
        this.uri = uri;
        this.folderPath = folderPath;
        this.width = width;
        this.height = height;
        this.format = format;
    }

    public void download() throws IOException {
        HttpURLConnection conn=null;
        FileOutputStream fileOutputStream=null;
        InputStream inputStream=null;


        try {
            URL url = new URL(uri);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setUseCaches(false);
            conn.setConnectTimeout(5000);
            conn.connect();


            String fileName = MessageFormat.format("{0}-{1}-{2}",width,height,UUID.randomUUID().toString());
            File folder = new File(folderPath);
            if(!folder.exists()) {
                folder.mkdirs();
            }
            File file = new File(folder,UUID.randomUUID().toString()+"."+format);
            fileOutputStream = new FileOutputStream(file);
            inputStream = conn.getInputStream();

            int len = 0;
            byte[] data = new byte[1024];
            while((len = inputStream.read(data))!=-1) {
                fileOutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(Objects.nonNull(inputStream)){
                inputStream.close();
            }
            if(Objects.nonNull(fileOutputStream)){
                fileOutputStream.close();
            }
            conn.disconnect();
        }

    }

    @Override
    public void run() {
        try {
            download();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
